const {Controller} = require('egg')

class CommentsController extends Controller{
    async add() {
        const {ctx} = this;
        const {videoid} = ctx.params
        const {_id} = ctx.userinfo
        const {content} = ctx.request.body
        try{
            const dbback = await ctx.service.comments.add({videoid,content,userid:_id})
            if(dbback){
                const {commenntcount} = await ctx.service.video.videodetail(videoid)
                await ctx.service.video.updatevideo(videoid,{commenntcount:commenntcount+1})
                await ctx.service.redis.createHotc(videoid,2)
                ctx.body = {code:1,msg:'评论成功'}
            }else{
                ctx.body = {code:0,msg:'评论失败'}
                ctx.status = 401
            }
        }catch{
            ctx.body = {code:0,msg:'评论失败'}
            ctx.status = 401
        }
        
    }

    async delete() {
        const {ctx} = this;
        const {commentid} = ctx.params
        const {_id} = ctx.userinfo   
        try{
            const dbback = await ctx.service.comments.getcomment(commentid)
            if(dbback.userid == _id){
                const dbback = await ctx.service.comments.delete(commentid)
                if(dbback){
                    const {commenntcount} = await ctx.service.video.videodetail(dbback.videoid)
                    await ctx.service.video.updatevideo(dbback.videoid,{commenntcount:commenntcount-1})
                    ctx.body = {code:1,msg:'删除成功'}
                }
            }else{
                ctx.body = {code:0,msg:'该评论没有删除权限'}
                ctx.status = 401
            }
        }catch{
            ctx.body = {code:0,msg:'删除失败'}
            ctx.status = 401
        }
        
    }

    async getcommentlist() {
        const {ctx} = this;
        const {videoid} = ctx.params
        const {page=1,pagesize=10} = ctx.query
        console.log(page,pagesize)
        try{
            const {dbback,count} = await ctx.service.comments.getcommentlist(page,pagesize,videoid)
            ctx.body = {code:1,msg:'获取成功',data:dbback,count}
        }catch{
            ctx.body = {code:0,msg:'获取失败'}
            ctx.status = 401
        }
    }
}

module.exports = CommentsController;